package no.ntnu.fp.gui;

import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import no.ntnu.fp.swingutil.EmailFormatter;

import run.Main;

import java.awt.Font;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.ParseException;
import java.awt.Color;

public class CreateNewUser extends JFrame {
	private JTextField txtName;
	private JTextField txtEmail;
	private JTextField txtUsername;
	private JPasswordField txtPassword;
	private EmailFormatter emailValidator = new EmailFormatter();
	
	public CreateNewUser() {
		setResizable(false);
		getContentPane().setBackground(Color.WHITE);
		initialiseUI();
		setLocationRelativeTo(null);
	}
	
	private void register() {
		String name = txtName.getText();
		String email = txtEmail.getText();
		String username = txtUsername.getText();
		String password = new String(txtPassword.getPassword());
		
		if (!isRegistrationValid(name, email, username, password)) {
			return;
		}
		
		try {
			registerUserInDatabase(name,email,username,password);
		}
		catch (Exception e) {
			showErrorMessage("The user could not be registered in the database. The error was: " + e.getMessage());
			return;
		}
		
		showSuccessMessage();
		showLogin();
	}
	
	private void showSuccessMessage() {
		JOptionPane.showMessageDialog(this, "The registration was successful!", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
	}
	
	private void registerUserInDatabase(String name,String email,String username,String password) {
		
		try {
			Main.dbConn.modifyDatabase("INSERT INTO `calendarsystem`.`employee` (" +
					"`employeeId` ," +
					"`name` ," +
					"`email` ," +
					"`username` ," +
					"`password`)" +
					"VALUES (NULL , '"+name+"', '"+email+"', '"+username+"','"+ password + "' )");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//this is where we will register the user in the database
		
	}
	
	private boolean userAlreadyExists(String username) {
		boolean userAlreadyExists = false; //we will (maybe?) check the database to see if the user already exists
		
		return userAlreadyExists;
		
	}
	
	private boolean isRegistrationValid(String name, String email, String username, String password) {
		if (name.length() < 5) {
			showErrorMessage("The name field must be 5 or more characters.");
			return false;
		}	
		
		if (username.length() < 5) {
			showErrorMessage("The username field must be 5 or more characters.");
			return false;
		}
		
		if (password.length() == 0) {
			showErrorMessage("You can't have an empty password.");
			return false;
		}
		
		try {
			emailValidator.stringToValue(email);
		} catch (ParseException e) {	
			showErrorMessage("Email format invalid.");
			return false;
		}
		
		return true;
	}
	
	private void showErrorMessage(String errorMessage) {
		JOptionPane.showMessageDialog(this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
	}
	
	private void showLogin() {
		this.setVisible(false);
		Login frame = new Login(); //returns us to login screen if we click cancel
		frame.setVisible(true);
	}
	
	private void initialiseUI() { //wall of code from design thing. Shows the registration screen.
		setMinimumSize(new Dimension(400, 270));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Calendar System - New user");
		getContentPane().setLayout(null);
		
		JLabel lblRegisterNewUser = new JLabel("Register new user");
		lblRegisterNewUser.setBounds(20, 9, 176, 28);
		lblRegisterNewUser.setFont(new Font("Tahoma", Font.PLAIN, 22));
		getContentPane().add(lblRegisterNewUser);
		
		JLabel lblName = new JLabel("Name");
		lblName.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblName.setBounds(86, 57, 36, 16);
		getContentPane().add(lblName);
		
		txtName = new JTextField();
		txtName.setBounds(124, 58, 178, 22);
		getContentPane().add(txtName);
		txtName.setColumns(10);
		
		JLabel lblEmailAddress = new JLabel("Email Address");
		lblEmailAddress.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblEmailAddress.setBounds(37, 88, 83, 16);
		getContentPane().add(lblEmailAddress);
		
		txtEmail = new JTextField();
		txtEmail.setBounds(124, 89, 178, 22);
		getContentPane().add(txtEmail);
		txtEmail.setColumns(10);
		
		JLabel lblUsername = new JLabel("Username");
		lblUsername.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblUsername.setBounds(61, 121, 58, 16);
		getContentPane().add(lblUsername);
		
		txtUsername = new JTextField();
		txtUsername.setBounds(124, 122, 178, 22);
		getContentPane().add(txtUsername);
		txtUsername.setColumns(10);
		
		JLabel lblPassword = new JLabel("Password");
		lblPassword.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblPassword.setBounds(64, 154, 63, 16);
		getContentPane().add(lblPassword);
		
		txtPassword = new JPasswordField();
		txtPassword.setBounds(124, 155, 178, 22);
		getContentPane().add(txtPassword);
		
		JButton btnOk = new JButton("Register");
		btnOk.setBounds(216, 189, 86, 29);
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				register();
			}
		});
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.setBounds(124, 188, 86, 30);
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showLogin();
			}
		});
		getContentPane().add(btnCancel);
		getContentPane().add(btnOk);
	}

}
